import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义游戏窗口尺寸
WIDTH = 800
HEIGHT = 600

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("赛车游戏")

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# 玩家赛车类
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 100))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH // 2
        self.rect.bottom = HEIGHT - 10
        self.speedx = 0

    def update(self):
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx = -5
        if keystate[pygame.K_RIGHT]:
            self.speedx = 5
        self.rect.x += self.speedx
        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.left < 0:
            self.rect.left = 0

# 障碍物类
class Obstacle(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill(BLACK)
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(3, 8)

    def update(self):
        self.rect.y += self.speedy
        if self.rect.top > HEIGHT + 10:
            self.rect.x = random.randrange(WIDTH - self.rect.width)
            self.rect.y = random.randrange(-100, -40)
            self.speedy = random.randrange(3, 8)

# 创建精灵组
all_sprites = pygame.sprite.Group()
obstacles = pygame.sprite.Group()

# 创建玩家赛车
player = Player()
all_sprites.add(player)

# 创建障碍物
for i in range(8):
    obs = Obstacle()
    all_sprites.add(obs)
    obstacles.add(obs)

# 游戏主循环
clock = pygame.time.Clock()
score = 0
font = pygame.font.Font(None, 36)

running = True
while running:
    clock.tick(60)

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 更新精灵
    all_sprites.update()

    # 碰撞检测
    hits = pygame.sprite.spritecollide(player, obstacles, False)
    if hits:
        running = False

    # 计分逻辑
    for obs in obstacles:
        if obs.rect.top > HEIGHT:
            score += 1
            obs.rect.x = random.randrange(WIDTH - obs.rect.width)
            obs.rect.y = random.randrange(-100, -40)
            obs.speedy = random.randrange(3, 8)

    # 绘制屏幕
    screen.fill(WHITE)
    all_sprites.draw(screen)

    # 显示得分
    score_text = font.render(f"得分: {score}", True, BLACK)
    screen.blit(score_text, (10, 10))

    # 更新显示
    pygame.display.flip()

# 游戏结束
pygame.quit()